package com.example.hemengqi


import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import java.io.*

class MainActivity : AppCompatActivity() {
    private val recyclerView by lazy { findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.recyclerView) }
    private val btnAddStudent by lazy { findViewById<androidx.appcompat.widget.AppCompatButton>(R.id.btnAddStudent) }
    private val REQUEST_CODE_ADD_STUDENT = 1
    private lateinit var studentList: MutableList<Student>
    private lateinit var studentAdapter: StudentAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        studentList = mutableListOf()
        loadStudents()

        recyclerView.layoutManager = LinearLayoutManager(this)
        studentAdapter = StudentAdapter(studentList)
        recyclerView.adapter = studentAdapter

        btnAddStudent.setOnClickListener {
            val intent = Intent(this, AddStudentActivity::class.java)
            startActivityForResult(intent, REQUEST_CODE_ADD_STUDENT)
        }
    }

    @Deprecated("Deprecated in Java")
    @SuppressLint("NotifyDataSetChanged")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_ADD_STUDENT && resultCode == RESULT_OK && data != null) {
            val newStudent = data.getSerializableExtra("newStudent") as Student
            studentList.add(newStudent)
            studentAdapter.notifyDataSetChanged()
            saveStudents()
        }
    }

    private fun loadStudents() {
        try {
            val fis = openFileInput("students.dat")
            val ois = ObjectInputStream(fis)
            studentList = ois.readObject() as MutableList<Student>
            ois.close()
            fis.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun saveStudents() {
        try {
            val fos = openFileOutput("students.dat", MODE_PRIVATE)
            val oos = ObjectOutputStream(fos)
            oos.writeObject(studentList)
            oos.close()
            fos.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}